package com.danciyixue.boot.dcyx.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.danciyixue.boot.core.security.util.SecurityUtils;
import com.danciyixue.boot.dcyx.mapper.UserStudyRecordsMapper;
import com.danciyixue.boot.dcyx.model.entity.DailyTimeRecords;
import com.danciyixue.boot.dcyx.model.vo.TodayStudyWordReportVO;
import com.danciyixue.boot.dcyx.service.DailyTimeRecordsService;
import com.danciyixue.boot.dcyx.service.UserStudyWordHistoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.danciyixue.boot.dcyx.mapper.UserStudyWordHistoryMapper;
import com.danciyixue.boot.dcyx.service.UserStudyWordHistoryService;
import com.danciyixue.boot.dcyx.model.entity.UserStudyWordHistory;
import com.danciyixue.boot.dcyx.model.form.UserStudyWordHistoryForm;
import com.danciyixue.boot.dcyx.model.query.UserStudyWordHistoryQuery;
import com.danciyixue.boot.dcyx.model.vo.UserStudyWordHistoryVO;
import com.danciyixue.boot.dcyx.converter.UserStudyWordHistoryConverter;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;

/**
 * 历史单词学习记录服务实现类
 *
 * @author youlaitech
 * @since 2025-06-15 16:20
 */
@Service
@DS("dcyx")
@RequiredArgsConstructor
public class UserStudyWordHistoryServiceImpl extends ServiceImpl<UserStudyWordHistoryMapper, UserStudyWordHistory> implements UserStudyWordHistoryService {

    private final UserStudyWordHistoryConverter userStudyWordHistoryConverter;
    private final DailyTimeRecordsService dailyTimeRecordsService;
    private final UserStudyRecordsMapper userStudyRecordsMapper;

    /**
    * 获取历史单词学习记录分页列表
    *
    * @param queryParams 查询参数
    * @return {@link IPage<UserStudyWordHistoryVO>} 历史单词学习记录分页列表
    */
    @Override
    public IPage<UserStudyWordHistoryVO> getUserStudyWordHistoryPage(UserStudyWordHistoryQuery queryParams) {
        Page<UserStudyWordHistoryVO> pageVO = this.baseMapper.getUserStudyWordHistoryPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }
    
    /**
     * 获取历史单词学习记录表单数据
     *
     * @param id 历史单词学习记录ID
     * @return 历史单词学习记录表单数据
     */
    @Override
    public UserStudyWordHistoryForm getUserStudyWordHistoryFormData(Long id) {
        UserStudyWordHistory entity = this.getById(id);
        return userStudyWordHistoryConverter.toForm(entity);
    }
    
    /**
     * 新增历史单词学习记录
     *
     * @param formData 历史单词学习记录表单对象
     * @return 是否新增成功
     */
    @Override
    public boolean saveUserStudyWordHistory(UserStudyWordHistoryForm formData) {
        UserStudyWordHistory entity = userStudyWordHistoryConverter.toEntity(formData);
        return this.save(entity);
    }
    
    /**
     * 更新历史单词学习记录
     *
     * @param id   历史单词学习记录ID
     * @param formData 历史单词学习记录表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateUserStudyWordHistory(Long id,UserStudyWordHistoryForm formData) {
        UserStudyWordHistory entity = userStudyWordHistoryConverter.toEntity(formData);
        return this.updateById(entity);
    }
    
    /**
     * 删除历史单词学习记录
     *
     * @param ids 历史单词学习记录ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteUserStudyWordHistorys(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的历史单词学习记录数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

    /**
     * 获取用户今日单词学习报告
     *
     * @return 用户今日单词学习报告
     */
    @Override
    public TodayStudyWordReportVO getTodayStudyWordReport() {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();

        // 获取今天的日期范围
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
        LocalDateTime todayEnd = LocalDate.now().atTime(LocalTime.MAX);

        // 创建返回对象
        TodayStudyWordReportVO result = new TodayStudyWordReportVO();

        // 1. 获取学习时长（从dcyx_daily_time_records表中获取time2字段）
        DailyTimeRecords timeRecord = getDailyTimeRecord(userId, todayStart);
        if (timeRecord != null && timeRecord.getEffectiveTime() != null) {
            // 计算有效学习时长（分钟）
            LocalDateTime startTime = todayStart;
            LocalDateTime endTime = timeRecord.getEffectiveTime();
            int minutes = (int) Duration.between(startTime, endTime).toMinutes();
            result.setStudyDuration(minutes);
        } else {
            result.setStudyDuration(0);
        }

        // 2. 获取学习单词数量（查询dcyx_user_study_records表中对应userid的今日记录数量）
        Integer wordCount = userStudyRecordsMapper.countTodayStudyWords(userId, todayStart, todayEnd);
        result.setWordCount(wordCount != null ? wordCount : 0);

        // 3. 计算学习速度（数量/时长，单位：个/小时）
        if (result.getStudyDuration() > 0) {
            double hours = result.getStudyDuration() / 60.0; // 转换为小时
            double speed = result.getWordCount() / hours;
            result.setStudySpeed(Math.round(speed * 100) / 100.0); // 保留两位小数
        } else {
            result.setStudySpeed(0.0);
        }

        return result;
    }

    /**
     * 获取用户当日时间记录
     *
     * @param userId 用户ID
     * @param today 今天的开始时间
     * @return 用户当日时间记录
     */
    private DailyTimeRecords getDailyTimeRecord(Long userId, LocalDateTime today) {
        LambdaQueryWrapper<DailyTimeRecords> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DailyTimeRecords::getUserId, userId)
                .eq(DailyTimeRecords::getRecordDate, today);

        return dailyTimeRecordsService.getOne(queryWrapper);
    }
}
